package com.application.Activity;


import it.unipr.ce.dsg.s2p.sip.Address;

import java.util.ArrayList;

import org.w3c.dom.Document;

import com.application.Controller.ActivityController;
import com.application.Controller.NetworkController;
import com.application.Controller.ReadWriteFileController;
import com.application.DataProvider.PartDAO;

import ReadWriteXML.COption;
import ReadWriteXML.CQuestion;
import ReadWriteXML.CResult;
import ReadWriteXML.CUsingQuestionList;
import ReadWriteXML.ReadXML;
import ReadWriteXML.WriteXML;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.DialogInterface;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckedTextView;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;

public class FrmDoTest extends ListActivity {
	private ArrayAdapter<String> arrayadapter;
	private CUsingQuestionList _tests;
	private int _countQuestion = 0;
	private int _questionIndex=0;//thu tu cua cau hoi hien tai tre arr cau hoi
	private int _time_min;
	private int _time_sec;
	private int _time;
	private String _timeBegin;
	private static int _status; 
	private TextView _txtTime;
	private ListView listView;
	private EditText _edtResultWriteQuestion;
	private Button _btnFeedback;
	private TextView _txtNumberQuestion;
	private TextView _txtTitle;
	private TextView _txtContent;
	private CQuestion _question;
	private Document _doc;
	static private String _fNameQues="";
	private String _fNameRes="";
	private String _pathQues= "";
	private CResult _result;
	private CResult _resultCurrent ;
	private int _flag =0;//flag de xac đinh co ghi hay khong
	private boolean _first = true;
	private AlertDialog.Builder _builder;
	private Thread _bg;
	private boolean isRunning;
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.frm_dotest);


		listView=getListView();
		//_fNameQues = ActivityController.get_fNameFullTest();
		getNameResult();
		_builder = new AlertDialog.Builder(this);

		/*chú thích ý nghĩa các biến:*/
		final ImageButton btnNext = (ImageButton) findViewById(R.id.dotest_btnnext);
		final ImageButton btnBack = (ImageButton) findViewById(R.id.dotest_btnback);
		_edtResultWriteQuestion = (EditText)findViewById(R.id.dotest_edtanswer);
		_btnFeedback = (Button) findViewById(R.id.dotest_btnfinish);
		_txtTitle = (TextView) findViewById(R.id.dotest_txttitle);

		/*sử lý đường dẫn động*/
		_pathQues = ReadWriteFileController.DIRECTORYTESTCONTENT+_fNameQues+".xml";
		Log.d("PEERDROID","_pathQues:" + _pathQues);
		_doc = ReadXML.BuildXML(_pathQues);
		if(_doc != null)
		{
			_tests =ReadXML.ReadReceive(_doc);
			_status = _tests.get_status();
			Log.d("PEERDROID","sau readReceive");
			//thiet lap thoi gian lam bai
			//			_txtTime = (TextView) findViewById(R.id.frmdotest_time);
			//_time_min = _tests.get_time();
			_time = _tests.get_time();
			Log.d("PEERDROID","_time : " + _time);
			_time_min = _time / 60;
			int timemin = _time_min;
			_time_sec = _time - _time_min * 60;
			_timeBegin = _tests.get_timeBegin();

			_txtNumberQuestion=(TextView) findViewById(R.id.dotest_numberquestion);
			int idPart = _tests.get_idPart();
			PartDAO pDao = new PartDAO(null);
			String title = null;
			title = _txtTitle.getText() +" bài tập cho chủ đề "+ pDao.getName(idPart)+" trong thời gian " + timemin + " phút.\nThời gian được tính bắt đầu từ " + _timeBegin;
			_txtTitle.setText(title);
			_countQuestion = ReadXML.readCount(_doc);//so luong cau hoi cua bai tap
			_questionIndex=0;
			_question = ReadXML.readQuestion(_doc, _questionIndex);//lay ra cau hoi tai vi tri thu k
			_result = ReadXML.readResult(_doc, _question.get_idQuestion(), _question.get_type());
			ShowQuesion(_question, _result);
			_txtNumberQuestion.setText("Câu "+Integer.toString(_questionIndex+1) + "/" + _countQuestion);
			//			if(_status == 1)
			//				showTime();
			//bat su kien click button next

			if(_countQuestion == 1)//chỉ có 1 câu hỏi
			{
				//				Log.d("PEERDROID","count question 1");
				btnBack.setEnabled(false);
				btnNext.setEnabled(false);

			}
			else{
				Log.d("PEERDROID","count khac 1");
				btnBack.setEnabled(false);
			}
			btnNext.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View arg0) {
					btnBack.setEnabled(true);
					if(_questionIndex<_countQuestion-1){
						if(_questionIndex<0)
						{
							_questionIndex=0;
						}

						//set data current
						handleDoTest(_question.get_type());

						//load next data
						_questionIndex=_questionIndex+1;
						_question = ReadXML.readQuestion(_doc, _questionIndex);
						_result = ReadXML.readResult(_doc, _question.get_idQuestion(), _question.get_type());
						ShowQuesion(_question, _result);
						_txtNumberQuestion.setText("Câu "+Integer.toString(_questionIndex+1) + "/" + _countQuestion);
					}
					if(_questionIndex>=_countQuestion-1){

						btnNext.setEnabled(false);
					}

				}
			});

			//bat su kien click button back
			btnBack.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					btnNext.setEnabled(true);
					if(_questionIndex>0){
						if(_questionIndex==_countQuestion)
						{
							_questionIndex=_questionIndex-1;
						}
						_questionIndex=_questionIndex-1;

						//set data current
						handleDoTest(_question.get_type());

						//load back data
						_question = ReadXML.readQuestion(_doc, _questionIndex);
						_result = ReadXML.readResult(_doc, _question.get_idQuestion(), _question.get_type());
						ShowQuesion(_question, _result);
						_txtNumberQuestion.setText("Câu "+Integer.toString(_questionIndex+1) + "/" + _countQuestion);				
					}
					if(_questionIndex<=0){
						//btnBack.setVisibility(0);
						btnBack.setEnabled(false);
					}
				}

			});

			_btnFeedback.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					doPressFeedback();
				}
			});
		}
	}

	private void doEndTime()
	{
		Log.d("PEERDROID","vào do end time");
		//set data current
		handleDoTest(_question.get_type());
		_bg.stop();
		String pathRes = ReadWriteFileController.DIRECTORYTESTCONTENT+"/"+_fNameRes + ".xml";
		WriteXML.copyResult(_pathQues, pathRes);
		String mess = "Đã hết thời gian làm bài, yêu cầu gửi bài làm!";
		_builder.setIcon(R.drawable.img_dialog);
		_builder.setMessage(mess)
		.setCancelable(false)
		.setPositiveButton("OK", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int id) {
				String s = NetworkController.get_ipHost();
				Address add = new Address(s);
				NetworkController.SendResultToTeacher(new Address(NetworkController.get_ipHost()), _fNameRes);
				Log.d("PEERDROID","pathQues :" + _pathQues);
				//cập nhật tình trạng status
				ReadWriteFileController.updateStatusUsingQuestionList(_fNameQues, 2);
				Log.d("PEERDROID","Đã gửi Thông tin Feedback");
				finish();
			}
		});
		AlertDialog alert = _builder.create();
		alert.getWindow().setBackgroundDrawable(new ColorDrawable(Color.argb(0, 255, 255, 255))); 
		alert.show();
	}
	private void doPressFeedback()
	{
		//set data current
		handleDoTest(_question.get_type());
		//		_bg.stop();
		//		_bg.suspend();
		String pathRes = ReadWriteFileController.DIRECTORYTESTCONTENT+"/"+_fNameRes + ".xml";
		WriteXML.copyResult(_pathQues, pathRes);
		String mess = "Bạn có chắc chắn đã hoàn thành bài tập?";
		_builder.setIcon(R.drawable.img_dialog);
		_builder.setMessage(mess)
		.setCancelable(false)
		.setPositiveButton("Đồng ý", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int id) {
				//tắt thread
				isRunning = false;
				String s = NetworkController.get_ipHost();
				Address add = new Address(s);
				//NetworkController.SendFeedbackToTeacher(new Address("192.168.2.1:5033"), _fNameRes);
				Log.d("PEERDROID","_fNameRes :" + _fNameRes);
				NetworkController.SendResultToTeacher(new Address(String.valueOf(NetworkController.get_ipHost())), _fNameRes);
				Log.d("PEERDROID","pathQues :" + _pathQues);
				//cập nhật tình trạng status
				ReadWriteFileController.updateStatusUsingQuestionList(_fNameQues, 2);
				Log.d("PEERDROID","Đã gửi Thông tin Feedback");
				finish();
			}
		})
		.setNegativeButton("Huỷ", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int id) {
				dialog.cancel();
			}
		});
		AlertDialog alert = _builder.create();
		alert.getWindow().setBackgroundDrawable(new ColorDrawable(Color.argb(0, 255, 255, 255))); 
		alert.show();
	}
	private void handleDoTest(int type){
		switch (type) {
		case 1: //single choice
		{
			if(_flag == 1)
			{
				_doc = WriteXML.updateResult(_doc, _pathQues, _resultCurrent);
				_resultCurrent.removeAllChoice();
				_flag = 0;
			}
			break;
		}	
		case 2: //multichoice
		{
			if(_flag == 1)
			{
				_doc = WriteXML.updateResult(_doc, _pathQues, _resultCurrent);
				_resultCurrent.removeAllChoice();
				_flag = 0;
				_first = true;
			}
			break;
		}
		case 3: //true false
		{
			if(_flag == 1)
			{
				_doc = WriteXML.updateResult(_doc, _pathQues, _resultCurrent);
				_resultCurrent.removeAllChoice();
				_flag = 0;
			}
			break;
		}
		case 5:
		{
			_resultCurrent= new CResult();
			_resultCurrent.setIDQuestion(_question.get_idQuestion());
			_resultCurrent.setType(_question.get_type());
			_resultCurrent.addChoice(_edtResultWriteQuestion.getText().toString());
			_doc = WriteXML.updateResult(_doc, _pathQues, _resultCurrent);
			_edtResultWriteQuestion.setText("");
		}
		}
	}

	@Override
	protected void onStart() {
		// TODO Auto-generated method stub
		super.onStart();
		Log.d("PEERDROID","vao onstart do test");
	//	ActivityController.setPeerActivity(this);
	}
	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		//ActivityController.setPeerActivity(this);
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		//		ShowSubjectList();	
		Log.d("PEERDROID", "vao resume");
	//	ActivityController.setPeerActivity(this);
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
	}

	private int getPos(ArrayList<COption> optList, int id)
	{
		int index = -1;
		int i = 0;
		for(COption o: optList)
		{
			if(o.get_idDetail() == id)
				index = i;
			i++;
		}
		return index;
	}

	//ham lay danh sach cau tra loi cua cau hoi multichoice
	private ArrayList<Integer> getPosMultiChoice(ArrayList<COption> optList, ArrayList<String> id)
	{
		ArrayList<Integer> arrIndex=new ArrayList<Integer>();
		for(int j=0;j<id.size();j++){
			int temp=getPos(optList, Integer.parseInt(id.get(j)));
			arrIndex.add(temp);

		}
		return arrIndex;
	}

	private void ShowQuesion(CQuestion question, CResult result){
		_txtContent = (TextView) findViewById(R.id.dotest_txtquestion);
		_txtContent.setText(question.get_content().toString());

		int type = question.get_type();

		ArrayList<String> optionList = new ArrayList<String>();
		switch(type)
		{
		case 1: //single choice
		{

			int n= question.get_listOption().size();
			//lay noi dung
			for(int i=0; i<n; i++){
				optionList.add(question.get_listOption().get(i).get_content());
			}

			//hien thi noi dung
			listView.setEnabled(true);
			listView.setVisibility(View.VISIBLE);
			arrayadapter = new ArrayAdapter<String>(this, R.layout.listrow_singlechoice,R.id.listrow_txtcautraloisingle, optionList);
			listView.setAdapter(arrayadapter);
			listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
			listView.getCheckedItemPosition();

			//lay gia tri khoi tao:
			if(result!= null)
			{
				int pos = getPos(question.get_listOption(), Integer.valueOf(result.getChoice().get(0)));

				//set gia tri cho radio button
				//listView.getChildAt(3).setClickable(true);
				getListView().setItemChecked(pos, true);

			}
			break;
		}
		case 2: //multi choice
		{
			int n= question.get_listOption().size();
			//lay noi dung
			for(int i=0; i<n; i++){
				optionList.add(question.get_listOption().get(i).get_content());
			}

			//hien thi noi dung:
			listView.setEnabled(true);
			listView.setVisibility(View.VISIBLE);
			arrayadapter = new ArrayAdapter<String>(this, R.layout.listrow_multichoice,R.id.listrow_txtcautraloi, optionList);
			listView.setAdapter(arrayadapter);
			listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
			listView.getCheckedItemPosition();

			//lay gia tri khoi tao:
			if(result!= null)
			{
				//int pos = getPos(question.get_listOption(), Integer.valueOf(result.getChoice().get(0)));
				ArrayList<Integer> pos = getPosMultiChoice(question.get_listOption(), result.getChoice());
				for(int i=0;i<pos.size();i++){
					getListView().setItemChecked(pos.get(i), true);
				}
			}
			break;
		}
		case 3: //true false
		{
			optionList.add("True");
			optionList.add("False");

			//hien thi noi dung

			listView.setEnabled(true);
			listView.setVisibility(View.VISIBLE);
			arrayadapter = new ArrayAdapter<String>(this, R.layout.listrow_truefalse,R.id.listrow_txtcautraloi, optionList);
			listView.setAdapter(arrayadapter);
			listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
			listView.getCheckedItemPosition();

			//lay gia tri khoi tao:
			if(result!= null)
			{
				//int pos = getPos(question.get_listOption(), Integer.valueOf(result.getChoice().get(0)));
				if(Integer.valueOf(result.getChoice().get(0))==1)
					getListView().setItemChecked(0, true);
				else
					getListView().setItemChecked(1, true);
				//set gia tri cho radio button


			}
			break;
		}
		case 4: //noi cot
		{
			break;
		}
		case 5: //writequest
		{
			EditText edtcautraloi = (EditText) findViewById(R.id.dotest_edtanswer);
			edtcautraloi.setEnabled(true);
			edtcautraloi.setVisibility(1);
			listView.setEnabled(false);
			listView.setVisibility(View.GONE);
			//lay gia tri khoi tao:
			if(result!= null)
			{
				_edtResultWriteQuestion.setText(result.getChoice().get(0));

			}
			break;
		}
		}

	}

	//thread can thoi gian lam bai
	private void showTime(){
		Log.d("PEERDROID","vào show time");
		if(_time_sec < 10)
			_txtTime.setText(_time_min + ":0" + _time_sec);
		else
			_txtTime.setText(_time_min + ":" + _time_sec);
		isRunning = true;
		_bg =  new Thread(new Runnable() {
			@Override
			public void run() {
				try {
					Log.d("PEERDROID","vào run");
					Log.d("PEERDROID","time" + _time);
					Log.d("PEERDROID","_time_min" + _time_min);
					Log.d("PEERDROID","_time sec: " + _time_sec);
					while(_time > 0 && isRunning) {
						if(_time_sec == 0)
						{
							_time_sec = 60;
							_time_min--;
						}
						Thread.sleep(1000);
						handler.sendMessage(handler.obtainMessage());
					}
					if(isRunning)
						ActivityController.handler.post(new Runnable() {

							@Override
							public void run() {
								// TODO Auto-generated method stub
								doEndTime();
							}
						}) ;
				}
				catch (Throwable t) {
				}
				////				finalize()
				//				{
				//					
				//				}
			}
		});
		_bg.start();
		Log.d("PEERDROID","sau start");
	}
	Handler handler=new Handler() {
		@Override
		public void handleMessage(Message msg) {
			Log.d("PEERDROID","Vào hander");
			_time--;
			_time_sec--;
			if(_time_sec < 10)
				_txtTime.setText(_time_min + ":0" + _time_sec);
			else _txtTime.setText(_time_min + ":" + _time_sec);
		}
	};

	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		super.onListItemClick(l, v, position, id);


		ArrayList<COption> optionList = _question.get_listOption();
		int idQs = _question.get_idQuestion();
		int typeQs = _question.get_type();

		if(_first == true && typeQs ==2)
		{
			_resultCurrent = new CResult();
			if(_result != null)
				_resultCurrent.copyAllChoice(_result);
			_first = false;
		}
		if(typeQs != 2)
			_resultCurrent = new CResult();
		_resultCurrent.setIDQuestion(idQs);//set id cau hoi
		_resultCurrent.setType(typeQs);//set loai 
		switch(typeQs)
		{
		case 1: //single choice
		{
			//String content = optionList.get(position).get_content();
			int iddetail = optionList.get(position).get_idDetail();
			_resultCurrent.addChoice(Integer.toString(iddetail));//add cau hoi, neu mul thi add n lan*/

			//gan flag de ghi
			_flag=1;

			break;
		}
		case 2: //multi
		{
			String content = optionList.get(position).get_content();
			int iddetail = optionList.get(position).get_idDetail();
			if(((CheckedTextView) v).isChecked()==false){
				content = optionList.get(position).get_content();
				iddetail = optionList.get(position).get_idDetail();
				_resultCurrent.addChoice(Integer.toString(iddetail));
				_flag=1;
			}
			else
			{
				content = optionList.get(position).get_content();
				iddetail = optionList.get(position).get_idDetail();
				_resultCurrent.removeChoice(Integer.toString(iddetail));//xoa mot lua chon
				_flag=1;
			}
			break;
		}
		case 3: //True false
		{
			String contentans = ((TextView) v).getText().toString();
			_resultCurrent.setIDQuestion(idQs);//set id cau hoi
			_resultCurrent.setType(typeQs);//set loai ch
			if(contentans.equals("True"))
			{
				_resultCurrent.addChoice(Integer.toString(1));
			}
			else{
				_resultCurrent.addChoice(Integer.toString(0));
			}
			//gan flag de ghi
			_flag=1;

			break;
		}
		case 4: //noi cot
		{

		}
		}
	}

	public static void set_fNameQues(String _fNameQues) {
		FrmDoTest._fNameQues = _fNameQues;
	}

	public static String get_fNameQues() {
		return _fNameQues;
	} 

	private void getNameResult()
	{
		String[] temp = _fNameQues.split("_");
		_fNameRes = temp[0]+ "_"+temp[1] + "_Result_" + temp[3];
	}

	public static void set_status(int _status) {
		FrmDoTest._status = _status;
	}

	public static int get_status() {
		return _status;
	}

	public void set_time(int _time) {
		this._time = _time;
	}

	public int get_time() {
		return _time;
	}
}




















